/**
 * 
 */
package com.randis.dailyplanner.dao;

import java.util.List;
import java.util.UUID;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.randis.dailyplanner.ServiceLocator;
import com.randis.dailyplanner.domain.User;

/**
 *  
 * 
 * @author alpe
 */
public class UserDao {
	
	private static final PersistenceManagerFactory pmfInstance = ServiceLocator.getInstance().getPMFInstance();
	
    public User getUser(String id) {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	User user = null;
    	try {
    		user = pm.getObjectById(User.class, id);
        	pm.detachCopy(user); 
    	} finally {
            pm.close(); 
    	}

    	return user;
    }

    public User findUser(String login) {
    	String queryString = "select from " + User.class.getName() + " where login=='" + login + "'";
    	List<User> users = doListUsers(queryString);
    	if (users.size() >= 1)
    		return users.get(0);
    	
    	return null;
    }

    public User saveUser(User user) {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	Transaction tx = pm.currentTransaction();
    	
    	try {
    		tx.begin();
    		if (user.getId() == null) {
    			user.setId("u" + UUID.randomUUID().toString());
    		}
    		user = pmfInstance.getPersistenceManager().makePersistent(user);
    		tx.commit();
    	} finally {
    		if (tx.isActive()) {
                tx.rollback();
            }
        	pm.close();
    	}
    	return user;
    }

	public List<User> list() {
    	String queryString = "select from " + User.class.getName();
		return doListUsers(queryString);
    }

    public void deleteUser(String id) {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	Transaction tx = pm.currentTransaction();
    	
    	try {
    		tx.begin();
    		User user = pm.getObjectById(User.class, id);
    		pm.deletePersistent(user);
    		tx.commit();
    	} finally {
    		if (tx.isActive()) {
                tx.rollback();
            }
        	pm.close();
    	}
    }

	private List<User> doListUsers(String queryString) {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	Query query = pm.newQuery(queryString);
    	
    	List<User> users = null;
    	
        try {
        	users = (List<User>) query.execute();
        	pm.detachCopyAll(users); 
        } finally {
        	query.closeAll();
            pm.close(); 
        }
        
		return users;
	}
}
